# Copyright (C) 2018 by Camptocamp
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
import logging


_logger = logging.getLogger(__name__)


class MrpProduction(models.Model):
    _inherit = 'mrp.production'
    
    # @override
    def _generate_finished_moves(self):
        # _logger.info('_generate_finished_moves %s',self.product_id.name)
        move = self.env['stock.move'].create({
            'name': self.product_id.name,#原来是self.name是不对的
            'date': self.date_planned_start,
            'date_expected': self.date_planned_start,
            'picking_type_id': self.picking_type_id.id,
            'product_id': self.product_id.id,
            'product_uom': self.product_uom_id.id,
            'product_uom_qty': self.product_qty,
            'location_id': self.product_id.property_stock_production.id,
            'location_dest_id': self.location_dest_id.id,
            'company_id': self.company_id.id,
            'production_id': self.id,
            'warehouse_id': self.location_dest_id.get_warehouse().id,
            'origin': self.name,
            'group_id': self.procurement_group_id.id,
            'propagate': self.propagate,
            'move_dest_ids': [(4, x.id) for x in self.move_dest_ids],
        })
        move._action_confirm()
        return move
    # @override
    def _generate_raw_move(self, bom_line, line_data):
        stock_move = super(MrpProduction, self)._generate_raw_move(bom_line,line_data)
        stock_move.write({'name':bom_line.product_id.name})
        return stock_move

    @api.multi
    def button_mark_done(self):
        re = super(MrpProduction, self).button_mark_done()
        for stock_move in self.move_raw_ids:
            for account_move in stock_move.account_move_ids:
                account_move.write({'ref':self.name})
        for stock_move in self.move_finished_ids:
            for account_move in stock_move.account_move_ids:
                account_move.write({'ref':self.name})
        return re